package l2;

import java.util.Arrays;

public class SeqList<T> implements List<T> {
    private static final int DEFAULT_CAPACITY = 10;
    private Object []data;
    private int size;
    public SeqList(int initCap){
        if(initCap < 0){
            throw new IllegalArgumentException("非法容量"+initCap);
        }
        data = new Object[initCap];
        size = 0;
    }
    public SeqList(){
        this(DEFAULT_CAPACITY);
    }

    public void clear(){
        size = 0;
        data = new Object[DEFAULT_CAPACITY];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void insert(int index, T value) {
        checkIndex(index,size+1);
        if (size == data.length){
            grow();
        }
        for (int i = size; i > index; i--) {
            data[i] = data[i - 1];
        }
        data[index]=value;
        size++;

    }

    private void checkIndex(int index,int limit) {
        if(index < 0 || index >= limit){
            throw new IndexOutOfBoundsException("索引越界"+index);
        }
    }
    private void grow(){
        int newCapacity = data.length * 2;
        data = Arrays.copyOf(data, newCapacity);
    }


    @Override
    public void remove(int index) {
        checkIndex(index,size);
        for (int i = index; i < size - 1; i++) {
            data[i] = data[i + 1];
        }
        data[size - 1] = null;
        size--;
    }

    @Override
    public int search(T value) {
        for (int i = 0; i < size; i++) {
            if(data[i].equals(value)){
                return i;
            }
        }
        return -1;
    }

    @Override
    public T visit(int index) {
        checkIndex(index);
        return (T) data[index];
    }

    private void checkIndex(int index) {
        if(index < 0 || index > size-1){
            throw new IndexOutOfBoundsException("索引越界"+index);
        }
    }
    @Override
    public void traverse() {
        for (int i = 0; i < size; i++) {
            System.out.println(data[i]+"");
        }
    }
}
